<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 订单
 * @author Administrator
 *
 */
class Time extends MY_Controller {
    private $tbOrder = 'consumer_order';
    private $tbUser = 'consumer';
    private $tbMerUser = 'merchant';
	public function __construct(){
		parent::__construct();
	}

	/**
	 * 每隔一分钟
	 */
	public function minute(){

		$this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
		$this->loadModel('ConsumerMessageModel', 'mMessage', 'consumer');
		$this->loadModel('ConsumerUserModel', 'mConsumer', 'consumer');
        $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
        $this->loadModel('MerchantMessageModel', 'mMerMsg', 'merchant');
        $this->loadModel('ConsumerPostalCardModel', 'mPostalCard','consumer');
        $this->loadModel('ConsumerPromotionModel', 'mPromotion', 'consumer');

        $config = $this->mSetting->get('reduce_stock,aftersale_limite_day,share_percent');

        /**
         * 未支付 已过期的订单
         *------------------------------------------------------------------------------------------------------------
         */
		$page = 1;
        $pageNumber = 250;
		while (true){
            $orderData = array();
            $pushData = array();
            $msgData = array();
            $postal = array();
			$this->db->select('o.id,o.consumer_id,o.expense_type,o.postal_card,u.jpush_code')
                     ->join($this->tbUser.' u', 'u.id = o.consumer_id')
                     ->where('o.status', 1)
                     ->where('o.addtime <',(time() - getCustomConfig('order_expire') * 60))
                     ->limit($pageNumber, ($page - 1) * $pageNumber)
                     ->group_by('o.id');
			$list = $this->mOrder->getAll($this->tbOrder.' o');

			if( ! $list){
				break;
			}

            foreach ($list as $v){
                //商品增加库存
                if ($config['reduce_stock'] == 1){
                    //下单时减少
                    $result = $this->mOrder->reduceStocks($v['id'], true);
					
                    if($result['status'] == 0){
						p($result);
                        break;
                    }
                }
			    $pushData[] = $v['jpush_code'];
                $orderData[] = array(
                    'id' => $v['id'],
                    'status' => 7
                );
                //消息
                $msgData[] = array(
                    'consumer_id' => $v['consumer_id'],
                    'type' => 3,
                    'title' => '订单关闭',
                    'content' => '支付超时，订单已自动关闭',
                    'order_id' => $v['id'],
                    'addtime' => time()
                );
                if($v['jpush_code']){
                    jpush('订单关闭','支付超时，订单已自动关闭', 1, $pushData, 3, $v['id'], $v['expense_type']);
                }

                if($v['postal_card'] > 0){
                    $postal[] = array(
                        'order_id' => 0,
                        'status' => 1,
                        'usedtime' => '',
                    );

                }
            }
			
            if($orderData){
			    $this->mOrder->saveBatch($orderData, '', array(), 'id');
			    $this->mMessage->saveBatch($msgData);
			    $this->mPostalCard->saveBatch($postal, 'order_id');
            }


            $page ++;

		}

        /**
         * 未评价且超过售后时间的发送分享红包
         */

        $page = 1;
        $pageNumber = 250;
        while (true) {
            $orderData = array();
            $this->db->select('o.id,o.consumer_id,o.param,o.expense_type,u.parent_id,o.type,o.reality_amount')
                ->join($this->tbUser . ' u', 'u.id = o.consumer_id')
                ->where('o.status', 4)
                ->where('u.status', 2)
                ->where('o.after_sale', 1)
                ->where('o.confirmtime <', (time() - $config['aftersale_limite_day'] * 60 * 60))
                ->limit($pageNumber, ($page - 1) * $pageNumber)
                ->group_by('o.id');
            $list = $this->mOrder->getAll($this->tbOrder . ' o');

            if (!$list) {
                break;
            }

            foreach ($list as $v) {
                //存在推荐人
                $parentInfo = [];
                if($v['parent_id'] > 0){
                    if($config['share_percent'] > 0){
                        $balanceLog = [
                            'consumer_id' => $v['parent_id'],
                            'type' => 7,
                            'pay_type' => 7,
                            'param' => $v['id'],
                            'amount' => sprintf('%.2f', ($v['reality_amount'] * $config['share_percent'])/100),
                            'status' => 2,
                            'addtime' => time(),
                            'confirm_time' => time(),
                        ];
                        $parentInfo = $this->mConsumer->getInfo($v['parent_id']);
                        if ( ! $this->mConsumer->saveBuyLog($balanceLog)){

                            $this->appReturn(0,'保存失败');
                        }
                        $cData= [
                            'id' => $v['parent_id'],
                            'balance' => $parentInfo['balance'] + $balanceLog['amount'],
                        ];

                        if ( ! ($this->mConsumer->save($cData, 'id'))){

                            $this->appReturn(0,'分享数据保存失败');
                        }
                    }

                   if($parentInfo){
                       //首单 分享注册送红包
                       $this->db->select('id,code')
                           ->where_in('status', [4, 5])
                           ->where('consumer_id', $v['consumer_id']);
                       $count = $this->mOrder->count($this->tbOrder);
                        if($count == 1){
                            $this->db->select('id,name,type,money,surplus_number')
                                ->where(array('type' => 1,'status'=> 2,'surplus_number >' => 0,'send_start_time <='=> time(),'send_end_time >=' => time()));
                            $bonusList = $this->mPromotion->getAll($this->mPromotion->tbBonus);
                            if($bonusList){
                                $bA = array();
                                $else = array();
                                foreach ($bonusList as $vv){
                                    $bA[] = array(
                                        'bonus_id' => $vv['id'],
                                        'type' => $vv['type'],
                                        'consumer_id' => $v['parent_id'],
                                        'money' => $vv['money'],
                                        'status' => 1,
                                        'param' => $v['id'],
                                        'addtime' => time()
                                    );
                                    $else[] = array(
                                        'id' => $vv['id'],
                                        'surplus_number' => $vv['surplus_number'] - 1,
                                    );
                                }
                                if(!($this->mPromotion->saveBonusLog($bA, 0, true))){

                                    $this->ajaxReturn(0, '红包赠送失败1');
                                }
                                //更新剩余红包数量
                                if(!($this->mPromotion->save($else, 0, true))){

                                    $this->ajaxReturn(0, '红包赠送失败2');
                                }
                            }

                        }

                   }
                }
                $orderData[] = ['id' => $v['id'],'status' => 5];
            }
            if ($orderData) {
                $this->mOrder->saveBatch($orderData, '', array(), 'id');
            }
            $page++;

        }

        /**
         * 已支付 商家接单已过期
         *------------------------------------------------------------------------------------------------------------
//         */
//        $page = 1;
//        $pageNumber = 250;
//
//        //接单时限内的订单
//        $expect_take_time = (int)getCustomConfig('expect_take_time');//接单有效时间
//
//        while (true){
//            $orderData = array();
//            $pushData = array();
//            $pushMerData = array();
//            $msgData = array();//用户消息
//            $msgMerData = array();//商家消息
//            $mobile = '';
//            $this->db->select('o.id,o.consumer_id,o.merchant_id,o.expense_type,u.jpush_code,o.wx_type,
//                                u.mobile,mu.jpush_code as merchant_jpush_code,o.reality_amount,o.pay_type,o.pay_code,o.code')
//                ->join($this->tbMerUser.' mu', 'mu.id = o.merchant_id')
//                ->join($this->tbUser.' u', 'u.id = o.consumer_id')
//                ->where('o.status', 2)
//                ->where('o.expense_type', 1)
//                ->where('o.pay_time <',(time() - $expect_take_time * 60))
//                ->limit($pageNumber, ($page - 1) * $pageNumber);
//
//            $list = $this->mOrder->getAll($this->tbOrder.' o');
//
//            if( ! $list){
//                break;
//            }
//
//            foreach ($list as $v){
//                $pushData[] = $v['jpush_code'];
//                $pushMerData[] = $v['merchant_jpush_code'];
//
////                $orderData[] = array(
////                    'id' => $v['id'],
////                    'status' => 6
////                );
//
//
//                $this->db->trans_begin();
//
//                $query = $this->mOrder->save(array('status'=>6),0,$v['id']);
//                if($query){
//                    //商家未接单前 取消已支付订单 原路退款
//                    $result = $this->mOrder->_OrderRefund($v['id'], $v['consumer_id'],$v['reality_amount'],$v['pay_type'],
//                        $v['wx_type'], $v['pay_code'], $v['code']);
//                    if($result['status'] == 0){
//                        $this->db->trans_rollback();
//                    }
//                    if($result['status'] == 1){
//                        //消息
//                        $msgData[] = array(
//                            'consumer_id' => $v['consumer_id'],
//                            'type' => 3,
//                            'title' => '订单已取消',
//                            'content' => '商家未受理',
//                            'order_id' => $v['id'],
//                            'addtime' => time()
//                        );
//                        $msgMerData[] = array(
//                            'merchant_id' => $v['merchant_id'],
//                            'type' => 3,
//                            'title' => '订单已取消',
//                            'content' => '超时未受理，订单已取消',
//                            'order_id' => $v['id'],
//                            'addtime' => time()
//                        );
//                        //给用户发送短信
//                        $mobile .= $v['mobile'].',';
//
//                        //删除查看记录
//                        $this->mMessage->deleteView($v['consumer_id'], 0, $v['id']);
//                        $this->mMerMsg->deleteView($v['merchant_id'],0,$v['id']);
//
//                        if($v['jpush_code']){
//                            jpush('订单已取消', '超时未受理，订单已取消', 1, array($v['jpush_code']), 3, $v['id'], $v['expense_type']);
//                        }
//                       if($v['merchant_jpush_code']){
//                           MerchantJpush('订单已取消', '超时未受理，订单已取消', 1, array($v['merchant_jpush_code']), 3, $v['id'], $v['expense_type']);
//                       }
//
//
//                        $this->db->trans_commit();
//                    }
//
//                }
//
//            }
//            if($mobile){
//                $msg = '您有一个订单因商家未能按时接单而被取消，很抱歉给您带来不便，现付款金额已原路退回，请注意查收。如有疑问请致电400-015-1819。';
//                sendSmsBatch(substr($mobile, 0, -1) , $msg);
//            }
//            if($msgData){
////                $this->mOrder->saveBatch($orderData, '', array(), 'id');
//                $this->mMessage->saveBatch($msgData, 0, 'order_id');
//
//            }
//            if($msgMerData){
//                $this->mMerMsg->saveBatch($msgMerData, 0, 'order_id');
//            }
//            $page ++;
//
//        }

    }
	

}
